package cn.jwm.interceptor;

import cn.jwm.annotation.JwmPermission;
import cn.jwm.constant.LoginConstant;
import cn.jwm.org.domain.Employee;
import cn.jwm.permission.service.IPermissionService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private IPermissionService iPermissionService;

    public boolean preHandel(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        String token = request.getHeader("token");
        Employee loginUser = (Employee) LoginConstant.loginMap.get(token);
        if(Objects.isNull(loginUser)){
            response.getWriter().println("{\"success\":false,\"message\":\"noLogin\"}");
            return false;
    }

        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            JwmPermission annotation = method.getAnnotation(JwmPermission.class);
            if (Objects.isNull(annotation)){
                return true;
            }
            String sn = method.getDeclaringClass().getSimpleName()+":"+method.getName();

            List<String> sns = iPermissionService.getPermissionSnsByLoginUserId(loginUser.getId());

            if(!sns.contains(sn)) {
                response.getWriter().println("{\"success\":false,\"message\":\"noPermission\"}");
                return false;
            }
        }
        return true;
    }
}
